package com.exposit.books.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.exposit.books.domain.Order;
import com.exposit.books.service.OrderService;


@Controller
@RequestMapping("/admin")
public class AdminCheckBooksFromPublishController {
	
	@Autowired
	private OrderService orderService;

	@RequestMapping(value = "/acheckbooks", method = { RequestMethod.GET })
	public String acheckbooks(Model model) {

		List<Order> listOrder = orderService.getAll();
		List<Order> listFromPublish = new ArrayList<Order>();

		for (int i = 0; i < listOrder.size(); i++) {
			if (listOrder.get(i).getStatus() == -3) {
				listFromPublish.add(listOrder.get(i));
			}
		}

		model.addAttribute("listFromPublish", listFromPublish);

		return "administrator/checkbooksfrompublish/acheckbooks";
	}

	@RequestMapping(value = "/markup{id}", method = { RequestMethod.GET })
	public String acheckbooks2(@PathVariable("id") Long id, Model model) {

		Order order = orderService.getOrderByID(id);

		model.addAttribute("order", order);
		model.addAttribute("path", id);

		return "administrator/checkbooksfrompublish/acheckbookschange";
	}

	@RequestMapping(value = "/markup{id}", method = { RequestMethod.POST })
	public ModelAndView acheckbooks2(
			@RequestParam(value = "markup", required = true) String markup,
			@PathVariable(value = "id") Long id, HttpServletRequest request,
			HttpSession session) {

		ModelAndView mav = new ModelAndView();

		Order order = orderService.getOrderByID(id);
		order.setStatus(0L);
		order.getBook().setPurchasePrice(order.getPublishPrice());
		order.getBook().setRetailPrice(Long.parseLong(markup));

		List<Order> listOrder = orderService.getAll();
		List<Order> listFromPublish = new ArrayList<Order>();

		for (int i = 0; i < listOrder.size(); i++) {
			if (listOrder.get(i).getStatus() == -3) {
				listFromPublish.add(listOrder.get(i));
			}
		}

		mav.addObject("listFromPublish", listFromPublish);
		mav.setViewName("administrator/checkbooksfrompublish/acheckbooks");

		return mav;
	}
	
}
